<?php

namespace app\admin\controller\order;

use app\admin\model\Cmdlog;
use app\admin\model\money\Platform;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\VbillService;
use app\common\controller\Backend;
use think\Db;
use think\Log;

/**
 * 店铺订单管理
 *
 * @icon fa fa-circle-o
 */
class Shoporder extends Backend
{

    /**
     * Shoporder模型对象
     * @var \app\admin\model\Shoporder
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $noNeedRight = ['open', 'clean', 'close'];
    protected $searchFields = 'order_no';


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shoporder;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('Shoporder.status', '<>', 'paying')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

            }
            $totalAmount = $this->model->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $todayAmount = $this->model->whereTime("create_time", 'today')->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $refundAmount = $this->model->whereTime("create_time", 'today')->where('status', 'refund')->sum('amount');

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['one' => $totalAmount, 'two' => $todayAmount, 'three' => $refundAmount]);


            return json($result);
        }
        return $this->view->fetch();
    }

    public function add($id = null)
    {

        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $order_no = $params['order_no'];
                $shopOrderModel = new \app\admin\model\Shoporder();
                $order = $shopOrderModel->where('order_no', $order_no)->find();

                if ($order['status'] == 'refund') $this->error('该订单已退款');
                if ($order['status'] == 'doing') $this->error('请先结束该订单，然后退款');

                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();

                //退实付
                $this->orderPayRefund($order, $shop, $params['refund_amount']);

                //退余额
                if ($order['balance'] > 0) {
                    $userBalanceModel = new Userbalance();
                    $where['user_id'] = $order['user_id'];
                    $where['order_id'] = $order['id'];
                    $where['type'] = 'out';
                    $where['from'] = 'qp';

                    $userBalanceModel->where($where)->delete();

                    //删除平台支出余额
                    $userAllBalance = new Userallbalance();
                    $userAllBalance->where('order_id', $order['id'])->where('type', 'out')->where('order_type', 'qp')->delete();

                    //删除平台商家收益
                    $shopBalanceProfit = new Shopbalanceprofit();
                    $shopBalanceProfit->where('order_id', $order['id'])->where('order_type', 'qp')->delete();
                }

                //团购券
                if ($order['tuan_id'] != -1) {
                    $userTuanModel = new Usertuan();
                    $userTuanModel->where('order_id', $order['id'])->update(['status' => 'unuse']);
                }

                //恢复预定
                $roomBookOrderModel = new Shoproombook();
                $roomBookOrderModel->where('order_id', $order['id'])->delete();

                $cleanRoomModel = new Roomclean();
                $cleanRoomModel->where('order_id', $order['id'])->delete();

                $this->success('退款成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function add2($id = null)
    {

        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $order_no = $params['order_no'];
                $shopOrderModel = new \app\admin\model\Shoporder();
                $order = $shopOrderModel->where('order_no', $order_no)->find();

                $orderStatus = $order['status'];
                if ($orderStatus == 'refund') {
                    $this->error("此订单已退款，无需操作");
                }

                //1、判断订单是否有现金支付
                if ($order['pay_amount'] > 0) {
                    //需退款金额  <= 订单实付金额 - 已退款金额；
                    $refund_amount = $params['refund_amount'];

                    // 订单已退款金额
                    $old_refund_amount = $order['refund_amount'];

                    // 退款后的支付金额
                    $new_pay_amount = $order['pay_amount'] - $refund_amount - $old_refund_amount;

                    if ($new_pay_amount < 0) $this->error("合计退款金额不能大于订单实付金额");
                    $req = array();
                    $req['mno'] = $this->mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = $refund_amount;

                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);
                    Log::info('==ret退款内容：' . $ret);
                    $result = json_decode($ret, true);

                    //判断原订单不一致的问题
                    if ($result['code'] != '0000') {
                        $this->error($result['msg']);
                    }
                    //判断订单是否退款成功
                    if ($result['respData']['bizCode'] != "0000") {
                        $this->error($result['respData']['bizMsg']);
                    }

                    $shopOrderProfitModel = new Shoporderprofit();
                    $userOrderProfitModel = new Userorderprofit();
                    //实付退款后，修改相应数据
                    switch ($new_pay_amount) {
                        //实付全退
                        case 0:
                            //清除店铺收益
                            $shopOrderProfitModel->where('type', 'order')->where('from', 'qp')->where('order_id', $id)->delete();
                            //清除个人收益
                            $userOrderProfitModel->where('type', 'order')->where('order_id', $id)->delete();
                            break;
                        // 实付部分退款
                        default:
                            //根据新的实际支付金额，更新店铺新收益
                            $shopModel = new Shop();
                            $shop = $shopModel->where('id', $order['shop_id'])->find();
                            $ratio = $shop['ratio'];
                            $pay_rate = $shop['pay_rate'];
                            $new_amount = formatMoney($new_pay_amount * ((100 - $ratio - $pay_rate) / 100));
                            $shopOrderProfitModel->where('type', 'order')->where('from', 'qp')->where('order_id', $id)->update(['amount' => $new_amount]);
                    }

                }

                //2、判断订单是否有使用余额
                if ($order['balance'] > 0) {
                    //删除店铺支出余额
                    $userBalanceModel = new Userbalance();
                    $userBalanceModel->where('order_id', $order['id'])->where('type', 'out')->delete();

                    //删除平台支出余额
                    $userAllBalance = new Userallbalance();
                    $userAllBalance->where('order_id', $order['id'])->where('type', 'out')->delete();

                    //删除平台商家收益
                    $shopBalanceProfit = new Shopbalanceprofit();
                    $shopBalanceProfit->where('order_id', $order['id'])->where('order_type', 'qp')->delete();
                }

                //3、判断订单是否有使用团购券
                if ($order['tuan_id'] != -1) {
                    $userTuanModel = new Usertuan();
                    $userTuanModel->where('id', $order['tuan_id'])->update(['status' => 'unuse']);
                }

                //4、判断订单是否使用美团券
                if (!empty($order['mt_code'])) {
                    Db::name('user_meituan_code')->where('mt_code', $order['mt_code'])->update(['status' => 'unuse']);
                }

                //5、判断订单是否使用抖音券
                if (!empty($order['dou_code'])) {
                    Db::name('user_dou_code')->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);
                }

                //退款完成，解锁释放包厢
                $bookModel = new Shoproombook();
                $roomCleanModel = new Roomclean();
                //更新订单表
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);

                //更新包厢预定表的记录
                $bookModel->where('order_id', $order['id'])->update(['status' => 'cancel']);

                //更新清扫表的记录
                if ($orderStatus != 'done') {
                    $roomCleanModel->where('order_id', $order['id'])->update(['status' => 'cancel']);
                }

                //查询是否有进行中的订单,不存在则，变更包厢状态
                $doingOrder = $shopOrderModel->where('room_id', $order['room_id'])->where('status', 'doing')->find();
                if (empty($doingOrder)) {
                    $shopRoom = new Shoproom();
                    $shopRoom->where('id', $order['room_id'])->update(['status' => 'free']);
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function open($id = NULL)
    {

        $user = $this->auth->getUser();
        $shopOrderModel = new \app\admin\model\Shoporder();
        $order = $shopOrderModel->where('id', $id)->find();

        if ($order['status'] == 'done' || $order['status'] == 'refund') {
            $this->error("订单状态 不允许开启");
        }
        if ($order['status'] == 'payed') {
            $time = strtotime("+20 minute", time());
            if ($order['book_start'] > $time || $time > $order['book_end']) {
                $this->error("订单开始和结束 不在当前时间范围内");
            } else {
                $minute = floor(($order['book_end'] - time()) % 86400 / 60);
                $sec = $minute * 60;
            }
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing']);
        } else {
            $minute = floor(($order['book_end'] - time()) % 86400 / 60);
            $sec = $minute * 60;
        }

        $shopBookModel = new Shoproombook();
        $shopBookModel->where('order_id', $order['id'])->update(['status' => 'doing']);

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('device_type', 'qp')->where('room_id', $order['room_id'])->find();

        $sn = $device['sn'];
        $req = array();
        $req['sec'] = $sec;
        $req['orderNo'] = $order['order_no'];
        $req['sn'] = $sn;
        $req['voice'] = "";

        $ret = http_post_json($this->cmdUrl, json_encode($req));
        $ret = json_decode($ret, true);
        $this->success('成功');

    }

    public function close($id = NULL)
    {


        $user = $this->auth->getUserInfo();
        $shopOrderModel = new \app\admin\model\Shoporder();
        $order = $shopOrderModel->where('id', $id)->find();

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('room_id', $id)->where('device_type', 'qp')->find();
        $shopOrderModel->where('id', $order['id'])->update(['status' => 'done']);


        $req = array();
        $req['sec'] = 0;
        $req['orderNo'] = getOrderSn();
        $req['sn'] = $device['sn'];
        $req['voice'] = "";

        $ret = http_post_json($this->cmdUrl, json_encode($req));
        $ret = json_decode($ret, true);


        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $user['id'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['room_id']]);

        $this->success('已关闭');

    }

    public function clean($id = NULL)
    {

        $shopOrderModel = new \app\admin\model\Shoporder();
        $order = $shopOrderModel->where('id', $id)->find();
        $room_id = $order['room_id'];
        $roomCleanModel = new Roomclean();
        $roomCleanModel->where('order_id', $id)->update(['status' => 'done']);
        $shopRoomModel = new Shoproom();
        $shopRoomModel->where('id', $room_id)->update(['is_clean' => 1]);
        $this->success('成功');
    }

    public function edit($id = NULL)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $order_no = $params['order_no'];
                $time = $params['book_start'];
                $shopOrderModel = new \app\admin\model\Shoporder();
                $order = $shopOrderModel->where('order_no', $order_no)->find();
                if ($order['status'] == 'done' || $order['status'] == 'refund') {
                    $this->error("订单状态 不允许修改");
                }
                if ($order['status'] != 'payed') {
                    $this->error("此订单已开始或者已完成，不支持更改");
                }

                $hour = ($order['book_end'] - $order['book_start']) / 3600;

                $time1 = strtotime($time);
                if ($time1 <= time()) {
                    $this->error("选择开始时间 要大于现在的时间");
                }

                $min = $hour * 60 + 30;//也包含保洁的时间
                $min2 = $hour * 60;
                $time2 = strtotime("+" . $min . " minute", $time1);
                $bookEnd = strtotime("+" . $min2 . " minute", $time1);

                $cleanStart = strtotime("+30 minute", $bookEnd);


                $shopRoomBookModel = new Shoproombook();
                $checkStart = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
                $checkEnd = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
                $checkEnd3 = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

                if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

                    $this->error("此时间段已预定，不能更改订单时间");
                }

                $shopCleanModel = new Roomclean();
                $shopOrderModel->where('id', $order['id'])->update(['book_start' => $time1, 'book_end' => $bookEnd]);
                $shopRoomBookModel->where('order_id', $order['id'])->update(['start_time' => $time1, 'end_time' => $bookEnd]);
                $shopCleanModel->where('order_id', $order['id'])->update(['start_time' => $bookEnd, 'end_time' => $cleanStart]);

                $this->success();

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //订单实付退款
    protected function orderPayRefund($order, $shop, $amount)
    {

        $shopOrderModel = new \app\admin\model\Shoporder();
        $refundAmount = 0.00;
        $new_pay_amount = 0.00;
        if ($amount > 0) {
            if ($amount > $order['pay_amount']) $this->error('退款金额不能大于支付金额');
            $new_pay_amount = formatMoney($order['pay_amount'] - $amount);
            $refundAmount = $amount;
        }

        if ($order['pay_amount'] > 0 && $refundAmount > 0) {

            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            $mno = $org['mno'];
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            error_log("==admin=app=refund===" . $ret);
            $result = json_decode($ret, true);

            //判断原订单不一致的问题
            if ($result['code'] != '0000') {
                $this->error($result['msg']);
            }

            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }

            $shopOrderProfitModel = new Shoporderprofit();
            $userOrderProfitModel = new Userorderprofit();
            $platformModel = new Platform();
            if ($new_pay_amount > 0) {
                //部分退款，重新划分商家收益、通道支付费以及平台收益
                $new_pay_rate = formatMoney($new_pay_amount * $shop['pay_rate'] / 100);//支付通道费
                $new_profit = formatMoney($new_pay_amount * (100 - $shop['ratio'] - $shop['pay_rate']) / 100);//商家收益
                $new_rate = formatMoney($new_pay_amount - $new_profit - $new_pay_rate);//平台收益
                $new_amount = formatMoney($order['amount'] - $amount);//新的订单金额
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $new_amount, 'pay_amount' => $new_pay_amount, 'pay_rate' => $new_pay_rate, 'rate' => $new_rate, 'update_time' => time()]);
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'qp')->update(['amount' => $new_profit]);

                $new_user_profit = formatMoney($new_pay_amount * $shop['agent_ratio'] / 100);
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->update(['amount' => $new_user_profit]);
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->update(['order_pay_amount' => $new_pay_amount, 'shop_amount' => $new_profit, 'rate' => $new_rate, 'agent_rate' => $new_user_profit]);

            } else {
                //全退，修改订单状态、删除收益记录
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);//修改订单状态
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'qp')->delete();
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->delete();
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->delete();
            }

        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }
    }

}
